//
//  CostVC.m
//  MyStock
//
//  Created by 刘翔 on 2024/12/10.
//

#import "CostVC.h"
#import "CostCell.h"
#import "CandidateStock.h"

@interface CostVC ()<StockViewDataSource,StockViewDelegate>
@property(nonatomic,strong)NSArray *dataList;
@property(nonatomic,strong)NSArray *sortDataList;
@property(nonatomic,strong) JJStockView *stockView;
@property(nonatomic,strong) NSMutableArray *headerNavModels;
@property(nonatomic, strong) NSMutableArray<ScreenNavBarItem *> *itemArray;

@end

@implementation CostVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.customNavBar.hidden = YES;
    
    self.stockView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    [self.view addSubview:self.stockView];
    [self.stockView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.equalTo(self.view);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);

    }];
    self.headerNavModels = [NSMutableArray array];
    NSArray *titles = @[@"价格",@"涨幅",@"距离",@"量比",@"评分"];
    for (int i = 0; i < titles.count; i++) {
        SortHeaerModel *model = [[SortHeaerModel alloc] initWithTitle:titles[i] normalImage:@"zt0" selectSingleImage:@"zt1" selectDoubleImage:@"zt2"];
        model.type = ItemSelelctTypeNone;
        model.itemCode = i + 50;
        [self.headerNavModels addObject:model];
    }
    self.stockView.jjStockTableView.mj_header = [LxResfreshHeader headerWithRefreshingBlock:^{
        [self loadData];
      }];
    [self.stockView.jjStockTableView.mj_header beginRefreshing];

}

- (void)sortTldStocksWith:(int)index withItemSelelctType:(ItemSelelctType)selectType{
    switch (index) {
        case 0:
        {
            if (selectType == 1 || selectType == 2) {
                self.sortDataList = [self.sortDataList sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                    CandidateStock *model1 = (CandidateStock *)obj1;
                    CandidateStock *model2 = (CandidateStock *)obj2;
                    if (selectType == 1) {
                        return [model1.last_px doubleValue] > [model2.last_px doubleValue];
                        
                    }else{
                        return [model1.last_px doubleValue] < [model2.last_px doubleValue];
                    }
                }];
                [self.stockView reloadStockView];
            }else{
                self.sortDataList = self.dataList;
                [self.stockView reloadStockView];
                
            }
            [self.stockView.jjStockTableView scrollToTop];
            
        }
            break;
        case 1:
        {
            if (selectType == 1 || selectType == 2) {
                
                self.sortDataList = [self.sortDataList sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                    CandidateStock *model1 = (CandidateStock *)obj1;
                    CandidateStock *model2 = (CandidateStock *)obj2;
                    if (selectType == 1) {
                        return [model1.px_change_rate doubleValue] > [model2.px_change_rate doubleValue];
                        
                    }else{
                        return [model1.px_change_rate doubleValue] < [model2.px_change_rate doubleValue];
                    }
                }];
                [self.stockView reloadStockView];
            }else{
                self.sortDataList = self.dataList;
                [self.stockView reloadStockView];
            }
            [self.stockView.jjStockTableView scrollToTop];
        }
            break;
        case 2:
            {
                if (selectType == 1 || selectType == 2) {
                    self.sortDataList = [self.sortDataList sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                        CandidateStock *model1 = (CandidateStock *)obj1;
                        CandidateStock *model2 = (CandidateStock *)obj2;
                        if (selectType == 1) {
                            return [model1.Diff doubleValue] > [model2.Diff doubleValue];

                        }else{
                           return [model1.Diff doubleValue] < [model2.Diff doubleValue];
                        }
                    }];
                    [self.stockView reloadStockView];
                }else{
                    self.sortDataList = self.dataList;
                    [self.stockView reloadStockView];

                }
            }
            break;
        case 3:
            {
                if (selectType == 1 || selectType == 2) {
                    self.sortDataList = [self.sortDataList sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                        CandidateStock *model1 = (CandidateStock *)obj1;
                        CandidateStock *model2 = (CandidateStock *)obj2;
                        if (selectType == 1) {
                            return [model1.vol_ratio doubleValue] > [model2.vol_ratio doubleValue];
                        }else{
                           return [model1.vol_ratio doubleValue] < [model2.vol_ratio doubleValue];
                        }
                    }];
                    [self.stockView reloadStockView];
                }else{
                    self.sortDataList = self.dataList;
                    [self.stockView reloadStockView];
                }
                
            }
            break;
            
        case 4:
            {
                if (selectType == 1 || selectType == 2) {
                    self.sortDataList = [self.sortDataList sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                        CandidateStock *model1 = (CandidateStock *)obj1;
                        CandidateStock *model2 = (CandidateStock *)obj2;
                        if (selectType == 1) {
                            return [model1.Score doubleValue] > [model2.Score doubleValue];

                        }else{
                           return [model1.Score doubleValue] < [model2.Score doubleValue];
                        }
                    }];
                    [self.stockView reloadStockView];
                }else{
                    self.sortDataList = self.dataList;
                    [self.stockView reloadStockView];

                }
                
            }
            break;
            
        default:
            break;
    }
}

- (void)userSelectIndexItem:(UITapGestureRecognizer *)tap {
    
    ScreenNavBarItem *itemView = (ScreenNavBarItem *)tap.view;
    NSInteger index = itemView.tag - 100;
    
    [self sortTldStocksWith:index withItemSelelctType:(itemView.currentType + 1) % 3];

    for (int i = 0; i < self.itemArray.count; i++) {
        SortHeaerModel *model = self.headerNavModels[i];
        ScreenNavBarItem *item = self.itemArray[i];
        ItemSelelctType current = item.currentType;
        if (index == i) {
            [item updateWithType:(current + 1) % 3];
            model.type = (current + 1) % 3;
        }else{
            [item updateWithType:0];
            model.type = 0;
        }
    }

}


- (void)loadData{
    
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [NSString stringWithFormat:@"%@/getcost/%d",MYSTOCKUrl,self.cost];
    entity.needCache = NO;
    entity.parameters = nil;
    
    [BANetManager ba_request_GETWithEntity:entity successBlock:^(id response) {
        NSDictionary *result = response;
        if ([result[@"code"] intValue] == 1) {
            
            self.dataList = [CandidateStock mj_objectArrayWithKeyValuesArray:result[@"data"]];
            self.sortDataList = [self.dataList mutableCopy];
            [self.stockView reloadStockView];
        }
        [self.stockView.jjStockTableView.mj_header endRefreshing];

    } failureBlock:^(NSError *error) {
        [self.stockView.jjStockTableView.mj_header endRefreshing];

        
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        
    }];
}

#pragma mark - Stock DataSource
- (NSUInteger)countForStockView:(JJStockView*)stockView{
    return self.sortDataList.count;
}

- (CGFloat)heightForHeadTitle:(JJStockView*)stockView{
    return 40;
}

- (UIView*)titleCellForStockView:(JJStockView*)stockView atRowPath:(NSUInteger)row{
    
    CandidateStock *model = self.sortDataList[row];
    UIView* bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SortTitleWidth, 70)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SortTitleWidth - 20, 35)];
    label.text = model.Name;
    label.textColor = Color_3;
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [UIFont systemFontOfSize:16];
    [bg addSubview:label];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, SortTitleWidth - 20, 35)];
    label1.text = model.Code;
    label1.textColor = Color_3;
    label1.textAlignment = NSTextAlignmentLeft;
    label1.font = [UIFont systemFontOfSize:16];
    [bg addSubview:label1];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    if (model.isSelected == 1) {
        imageView.hidden = NO;
    }else{
        imageView.hidden = YES;
    }
    imageView.frame = CGRectMake(0, 0, 16, 16);
    imageView.image = [UIImage imageNamed:@"hot"];
    [bg addSubview:imageView];
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bg);
        make.right.equalTo(bg);
    }];
    
    UIImageView *imageView1 = [[UIImageView alloc] init];
    if (model.IsWin == 1) {
        imageView1.hidden = NO;
    }else{
        imageView1.hidden = YES;
    }
    imageView1.frame = CGRectMake(0, 0, 16, 16);
    imageView1.image = [UIImage imageNamed:@"wujiaoxingyuanjiao"];
    [bg addSubview:imageView1];
    
    float offset = 0;
    if (model.isSelected == 1) {
        offset = 16;
    }
    [imageView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bg);
        make.right.equalTo(bg).offset(offset);
    }];
    return bg;
}

- (Class)cellForStockView:(JJStockView *)stockView atRowPath:(NSUInteger)row{
    return [CostCell class];
}

- (void)cellHandleContent:(JJStockView *)stockView withCell:(JJStockViewCell *)cell atRowPath:(NSUInteger)row{
    
    CostCell *myCell = (CostCell *)cell;
    CandidateStock *model = self.sortDataList[row];
    if (self.cost == 0) {
        myCell.timeL.text = model.cover15Time;

    }else{
        myCell.timeL.text = model.cover30Time;

    }
    
    NSString *topicstr = model.Topics;
    topicstr = [topicstr substringWithRange:NSMakeRange(1, topicstr.length - 2)];
    NSArray *tags = [topicstr componentsSeparatedByString:@","];
    NSMutableArray *marray = [NSMutableArray array];
    for (NSString *tag in tags) {
        NSString *newTag = [tag substringWithRange:NSMakeRange(1, tag.length - 2)];
        [marray addObject:newTag];
    }
    
    NSString *topicHotstr = model.TopicsHot;
    NSMutableArray *marrayHot = [NSMutableArray array];

    topicHotstr = [topicHotstr substringWithRange:NSMakeRange(1, topicHotstr.length - 2)];
    NSArray *hotTags = [topicHotstr componentsSeparatedByString:@","];

    if (topicHotstr.length > 2) {
        
        for (NSString *tag in hotTags) {
            NSString *newTag = [tag substringWithRange:NSMakeRange(1, tag.length - 2)];
            [marrayHot addObject:newTag];
        }
    }
    [myCell setTags:marray withHots:marrayHot];
}

- (UIView*)contentCellForStockView:(JJStockView*)stockView atRowPath:(NSUInteger)row{
    
    CandidateStock *model = self.sortDataList[row];
    UIView* bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SortTitleWidth * self.headerNavModels.count, 70)];
    for (int i = 0; i < self.headerNavModels.count; i++) {
        
        UIView *subBg = [[UIView alloc] initWithFrame:CGRectMake(i * SortItemWidth, 0, SortItemWidth, 40)];
        StockLabel* label = [[StockLabel alloc] initWithFrame:CGRectMake(0, 0, SortItemWidth, 70)];
        label.code = model.Code;
        label.text = @"--";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:16];
        [subBg addSubview:label];
        [bg addSubview:subBg];
        [self handleLabelWithIndex:i withModel:model label:label];
    }
    return bg;
}

- (UIColor *)getTextColorWithModel:(StockModel *)model{
    if ([model.px_change_rate doubleValue] > 0) {
        return Color_red;
    }else if ([model.px_change_rate doubleValue] == 0){
        return Color_3;
    }else{
        return Color_gree;
    }
}

- (void)handleLabelWithIndex:(int)index withModel:(CandidateStock *)model label:(StockLabel *)label{
    switch (index) {
        case 0:
            {
                __weak typeof(label) weakLabel = label;
                label.text = [NSString stringWithFormat:@"%.2f",[model.last_px doubleValue]];
                label.textColor = [self getTextColorWithModel:model];
                label.stockChangeHandle = ^(StockModel * _Nullable stockData) {
                    model.last_px = stockData.last_px;
                    model.px_change_rate = stockData.px_change_rate;
                    weakLabel.text = [NSString stringWithFormat:@"%.2f",[model.last_px doubleValue]];
                    weakLabel.textColor = [self getTextColorWithModel:model];
                };
                
            }
            break;
        case 1:
            {
                __weak typeof(label) weakLabel = label;
                label.text = [NSString stringWithFormat:@"%.2f%@",[model.px_change_rate doubleValue],@"%"];
                label.textColor = [self getTextColorWithModel:model];
                label.stockChangeHandle = ^(StockModel * _Nullable stockData) {
                    self.stockView.tag = 1;
                    model.px_change_rate = stockData.px_change_rate;
                    model.px_change_rate = stockData.px_change_rate;
                    weakLabel.text = [NSString stringWithFormat:@"%.2f%@",[model.px_change_rate doubleValue],@"%"];
                    weakLabel.textColor = [self getTextColorWithModel:model];

                };
                
            }
            break;
        case 2:
            {
                label.text = [NSString stringWithFormat:@"%.2f",[model.Diff doubleValue]];
                if ([model.Diff doubleValue] > 0) {
                    label.textColor = Color_gree;
                }else if ([model.Diff doubleValue] == 0){
                    label.textColor = Color_3;
                }else{
                    label.textColor = Color_red;
                }
                
                __weak typeof(label) weakLabel = label;
                label.stockChangeHandle = ^(StockModel * _Nullable stockData) {
                    double diff = ([stockData.last_px doubleValue] - [model.NowCost30 doubleValue]) / [model.NowCost30 doubleValue] * 100;
                    model.Diff = [NSString stringWithFormat:@"%2.f",diff];
                    weakLabel.text = [NSString stringWithFormat:@"%.2f",diff];
                    if (diff > 0) {
                        weakLabel.textColor = Color_gree;
                    }else if (diff == 0){
                        weakLabel.textColor = Color_3;
                    }else{
                        weakLabel.textColor = Color_red;
                    }
                };

            }
            break;
        case 3:
            {
                label.text = [NSString stringWithFormat:@"%.2f",[model.vol_ratio doubleValue]];
                if ([model.vol_ratio doubleValue] > 1) {
                    label.textColor = Color_red;
                }else{
                    label.textColor = Color_gree;
                }
                __weak typeof(label) weakLabel = label;
                label.stockChangeHandle = ^(StockModel * _Nullable stockData) {
                    model.vol_ratio = stockData.vol_ratio;
                    weakLabel.text = [NSString stringWithFormat:@"%.2f",[model.vol_ratio doubleValue]];
                    if([model.vol_ratio doubleValue] > 1) {
                        weakLabel.textColor = Color_red;
                    }else{
                        weakLabel.textColor = Color_gree;
                    }
                    
                };
                
            }
            break;
        case 4:{
            label.text = model.Score;
            
        }
            
        default:
            break;
    }
}
#pragma mark - Stock Delegate

- (UIView*)headRegularTitle:(JJStockView*)stockView{
    UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SortTitleWidth, 40)];
    
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SortTitleWidth - 20, 40)];
    label.text = @"名称";
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = Color_3;
    label.textAlignment = NSTextAlignmentLeft;
        
    [bg addSubview:label];
    return bg;
}

- (UIView*)headTitle:(JJStockView*)stockView{
    
    UIView* bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SortItemWidth * self.headerNavModels.count, 40)];
    [self.itemArray removeAllObjects];
    for (int i = 0; i < self.headerNavModels.count; i++) {
        ScreenNavBarItem *itemView = [[ScreenNavBarItem alloc] initWithItemModel:self.headerNavModels[i]];
        itemView.frame = CGRectMake(i * SortItemWidth, 0, SortItemWidth, 40);
        itemView.tag = 100 + i;
        [bg addSubview:itemView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userSelectIndexItem:)];
        [itemView addGestureRecognizer:tap];
        [self.itemArray addObject:itemView];

    }
    return bg;
}

- (void)didSelect:(JJStockView*)stockView atRowPath:(NSUInteger)row{
    CandidateStock *model = self.sortDataList[row];
    
    StockDetailDVC *vc = [[StockDetailDVC alloc] init];
    vc.dataList = self.sortDataList;
    vc.index = row;
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
//    StockDetailVC *vc = [[StockDetailVC alloc] init];
//    NSString *urlStr;
//    if([[model.Code substringToIndex:1] isEqualToString:@"6"]){
//        urlStr = [NSString stringWithFormat:@"https://wap.eastmoney.com/quote/stock/1.%@.html",model.Code];
//    }else{
//        urlStr = [NSString stringWithFormat:@"https://wap.eastmoney.com/quote/stock/0.%@.html",model.Code];
//    }
//
//    vc.url = [NSURL URLWithString:urlStr];
//    vc.name = model.Name;
//    vc.code = model.Code;
//
//    double c15 = [model.NowCost15 doubleValue];
//    double c30 = [model.NowCost30 doubleValue];
//    vc.lowPrice = [model.low doubleValue];
//    vc.cost15 = [NSString stringWithFormat:@"%.2f",c15];
//    vc.cost30 = [NSString stringWithFormat:@"%.2f",c30];
//    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)longTouch:(JJStockView*)stockView atRowPath:(NSUInteger)row atPoint:(CGPoint)point{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    CandidateStock *model = self.sortDataList[row];
   
    UITableViewCell *cell = [stockView.jjStockTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
    [FTPopOverMenu showForSender:cell withMenuArray:@[@"复制",@"添加"] imageArray:@[@"fuzhi",@"tianjia"] doneBlock:^(NSInteger selectedIndex) {
        if (selectedIndex == 0) {
            UIPasteboard *board = [UIPasteboard generalPasteboard];
            board.string = model.Code;
            [MBProgressHUD showSuccess:@"复制成功" toView:self.view];
        }else if(selectedIndex == 1){
            [PositionTool addPositionWithCode:model.Code];
        }
            
    } dismissBlock:^{
        
        
    }];
    
}

- (NSMutableArray<ScreenNavBarItem *> *)itemArray {
    if (!_itemArray) {
        _itemArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _itemArray;
}

- (JJStockView*)stockView{
    if(_stockView != nil){
        return _stockView;
    }
    _stockView = [JJStockView new];
    _stockView.dataSource = self;
    _stockView.delegate = self;
    return _stockView;
}

#pragma mark - JXCategoryListContentViewDelegate
- (UIView *)listView {
    return self.view;
}

- (void)listDidAppear {
    
}

- (void)listDidDisappear {
    
}

@end
